<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="名称" prop="title">
        <el-input v-model="dataForm.title" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item label="总价" prop="zj">
        <el-input
          v-model="dataForm.zj"
          tupe="numbber"
          @input="inputChangezj('maxCharacterCount')"
          minlength="1"
          placeholder="总价"
        ></el-input>
      </el-form-item>
      <el-form-item label="定价" prop="dj">
        <el-input
          v-model="dataForm.dj"
          tupe="numbber"
          @input="inputChangedj('maxCharacterCount')"
          minlength="1"
          placeholder="定价"
        ></el-input>
      </el-form-item>
      <el-form-item label="图片">
        <!-- <el-input v-model="dataForm.images" placeholder="图片"></el-input> -->
        <el-upload
          :action="url"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreviewss"
          :on-success="handleAvatarSuccesses"
          :on-remove="handleRemovess"
          :file-list="fileList3"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="封面">
        <!-- <el-input v-model="dataForm.headPhoto" placeholder="封面"></el-input> -->
        <el-upload
          class="avatar-uploader"
          :action="url"
          ref="upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="数量" prop="sl">
        <el-input v-model="dataForm.sl" placeholder="数量"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <!-- <el-input v-model="dataForm.status" placeholder="状态"></el-input> -->
        <el-select v-model="dataForm.status" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否首页展示" prop="sfzssy">
        <!-- <el-input v-model="dataForm.status" placeholder="状态"></el-input> -->
        <el-select v-model="dataForm.sfzssy" placeholder="请选择">
          <el-option
            v-for="item in homeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="跳转地址" prop="url">
        <!-- <el-input v-model="dataForm.status" placeholder="状态"></el-input> -->
        <el-select v-model="dataForm.url" placeholder="请选择">
          <el-option
            v-for="item in urlList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Vue from "vue";
import lodashGet from "lodash/get";
export default {
  data() {
    return {
      fileList3:[],
      dialogImageUrlss: "",
      dialogVisibless: false,
      url: "",
      imageUrl: "",
      visible: false,
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      imagesList: [],
      dataForm: {
        id: "",
        title: "",
        zj: "",
        dj: "",
        images: "",
        sl: "",
        headPhoto: "",
        status: ""
      },
      options: [
        {
          value: 0,
          label: "上架"
        },
        {
          value: 1,
          label: "下架"
        }
      ],
      homeList:[
          {
            value: 0,
            label: "不展示"
          },
          {
            value: 1,
            label: "展示"
          }
      ],
      urlList:[
          {
            value:'',
            label: "无"
          },
          {
            value: '/pages/writing/details/index',
            label: "详情"
          }
      ],
      dataRule: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        zj: [{ required: true, message: "总价不能为空", trigger: "blur" }],
        dj: [{ required: true, message: "定价不能为空", trigger: "blur" }],
        images: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        sl: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        headPhoto: [
          { required: true, message: "封面不能为空", trigger: "blur" }
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        sfzssy:  [{ required: true, message: "是否展示不能为空", trigger: "blur" }],
        url:[{ required: true, message: "跳转地址不能为空", trigger: "blur" }]
      }
    };
  },
  methods: {
    inputChangezj(data) {
      var min = 1;
      if (Number(this.dataForm.zj.replace(/[^\d]/g, "")) < min) {
        this.dataForm.zj = min;
      } else {
        this.dataForm.zj = this.dataForm.zj.replace(/[^\d]/g, "");
      }
    },
    inputChangedj(data) {
      var min = 1;
      if (Number(this.dataForm.dj.replace(/[^\d]/g, "")) < min) {
        this.dataForm.dj = min;
      } else {
        this.dataForm.dj = this.dataForm.dj.replace(/[^\d]/g, "");
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.dataForm.headPhoto = res.url;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isLt2M;
    },
    handleAvatarSuccesses(res, file, fileList) {
      this.imagesList.push(res.url);
      console.log("this.imagesList", this.imagesList);
      console.log("this.fileList3", this.fileList3);
    },
    handleRemovess(file, fileList) {
      let fileId = lodashGet(file, ["id"], "");
      if (fileId) {
        this.imagesList = this.imagesList.filter(item => item !== fileId);
      }
      console.log(file, fileList);
      console.log(this.imagesList);
    },
    handlePictureCardPreviewss(file) {
      this.dialogImageUrlss = file.url;
      this.dialogVisibless = true;
    },
    init(id) {
      if(!id) {
        this.imageUrl = ""
      }
      this.url = this.$http.adornUrl(
        `app/oss/upload?token=${this.$cookie.get("token")}`
      );
      this.dataForm.id = id || "";
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `sys/creativegoods/queryByid?id=${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.creativeGoods;
              let resImgData = data.creativeGoods.images.split(',');
              this.imagesList = resImgData
              this.fileList3 = resImgData.map(item => {
                return {
                  url: 'https://yunchenbucket.oss-cn-qingdao.aliyuncs.com/' + item,
                  id: item
                }
              });
              this.imageUrl = 'https://yunchenbucket.oss-cn-qingdao.aliyuncs.com/' + data.creativeGoods.headPhoto
              // var imglist = []
              // imglist =  data.creativeGoods.images.split(',')
              // imglist.forEach((item,index) => {
              //   imglist[index] = 'https://yunchenbucket.oss-cn-qingdao.aliyuncs.com/' + item
              // });
              // this.imagesList = imglist
              console.log(this.fileList3,'this.imagesListthis.imagesList')
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`sys/creativegoods/update`),
              method: "post",
              params: this.$http.adornParams({
                id: this.dataForm.id,
                title: this.dataForm.title,
                zj: this.dataForm.zj,
                dj: this.dataForm.dj,
                images: this.imagesList.toString(),
                sl: this.dataForm.sl,
                headPhoto: this.dataForm.headPhoto,
                status: this.dataForm.status,
                sfzssy: this.dataForm.sfzssy,
                url: this.dataForm.url
              })
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.imagesList = []
                    this.fileList3 = []
                    this.imageUrl = ''
                    this.$refs.upload.clearFiles();
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          } else {
            this.$http({
              url: this.$http.adornUrl(`sys/creativegoods/save`),
              method: "post",
              params: this.$http.adornParams({
                title: this.dataForm.title,
                zj: this.dataForm.zj,
                dj: this.dataForm.dj,
                images: this.imagesList.toString(),
                sl: this.dataForm.sl,
                headPhoto: this.dataForm.headPhoto,
                status: this.dataForm.status,
                sfzssy: this.dataForm.sfzssy,
                url: this.dataForm.url
              })
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.imagesList = []
                    this.fileList3 = []
                    this.imageUrl = ''
                    this.$refs.upload.clearFiles();
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        }
      });
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
